package com.junmeng.libfloating.util;

import android.graphics.Rect;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;


import java.util.Collections;
import java.util.List;

public class FragmentUtil {
    /**
     * 获得指定位置所在的Fragment
     *
     * @param fragmentActivity
     * @param touchX           指定位置坐标x
     * @param touchY           指定位置坐标y
     * @return
     */
    @Nullable
    public static Fragment findVisibleFragment(@NonNull FragmentActivity fragmentActivity, float touchX, float touchY) {
        List<Fragment> frags = fragmentActivity.getSupportFragmentManager().getFragments();

        Fragment find = findVisibleFragment(frags, touchX, touchY);
        return find;
    }

    private static Fragment findVisibleFragment(List<Fragment> frags, float touchX, float touchY) {
        if (frags == null) {
            return null;
        }
        Collections.reverse(frags);
        for (Fragment frag : frags) {
            if (frag != null && frag.isVisible()) {
                FragmentManager childFragmentManager = frag.getChildFragmentManager();
                Fragment find = findVisibleFragment(childFragmentManager.getFragments(), touchX, touchY);
                if (find != null) {
                    return find;
                }
                ViewGroup root = (ViewGroup) frag.getView();
                Rect pos = new Rect();
                root.getGlobalVisibleRect(pos);
                if (pos.contains((int) touchX, (int) touchY)) {
                    return frag;
                }
            }
        }
        return null;
    }
}